package com.ainiyar.springweb.service.impl;

import com.ainiyar.springweb.mapper.ConfigsMapper;
import com.ainiyar.springweb.pojo.entity.Configs;
import com.ainiyar.springweb.service.ConfigsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.ainiyar.springweb.pojo.entity.table.ConfigsTableDef.CONFIGS;

/**************************************
 * File Name : ConfigsServiceImpl
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/18  18:39
 * Desc :处理系统设置数据
 ***************************************/
@Service
public class ConfigsServiceImpl extends ServiceImpl<ConfigsMapper, Configs> implements ConfigsService {
    @Resource
    private ConfigsMapper configsMapper;

    @Override
    public boolean saveSettingData(Map<String, String[]> param, String type) {
        List<Configs> lis = handelSettingParam(param, type);
        boolean flag = true;
        if (Objects.equals(type, "sms")) {
            flag = saveSmsSetting(lis, type);
        } else {
            for (Configs record : lis) {
                Integer id = getSettingsId(record.getType(), record.getKey());
                if (id != null) {
                    record.setId(id);
                }
                if (configsMapper.insertOrUpdateSelective(record) == 0) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    @Override
    public Object getSettings() {
        String jsonResult;
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(CONFIGS.ALL_COLUMNS);
            List<Configs> list = configsMapper.selectListByQuery(queryWrapper);
            Map<String, Map<String, Object>> groupedConfigs = list.stream()
                    .collect(Collectors.groupingBy(
                            Configs::getType,
                            Collectors.toMap(Configs::getKey,
                                    config -> {
                                        if (Objects.equals(config.getType(), "sms")) {
                                            return getStringObjectMap(config);
                                        } else {
                                            if (config.getValue().startsWith("[") && config.getValue().endsWith("]")) {
                                                return Arrays.stream(config.getValue()
                                                                .substring(1, config.getValue().length() - 1)
                                                                .split(", "))
                                                        .map(s -> s.replaceAll("[\\[\\]]", "'"))
                                                        .toArray(String[]::new);
                                            } else {
                                                return config.getValue();
                                            }
                                        }
                                    })
                    ));

            ObjectMapper objectMapper = new ObjectMapper();
            jsonResult = objectMapper.writeValueAsString(groupedConfigs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return jsonResult;
    }

    /**
     * string数据转换 Map<String, Object>
     *
     * @param config 数据
     */
    private static Map<String, Object> getStringObjectMap(Configs config) {
        String input = config.getValue();
        // 去除大括号，并按逗号分割键值对
        String[] pairs = input.substring(1, input.length() - 1).split(", ");
        Map<String, Object> resultMap = new HashMap<>();
        for (String pair : pairs) {
            // 按等号分割键值对
            String[] keyValue = pair.split("=");
            String key = keyValue[0];
            Object value = keyValue[1]; // 这里值的类型是String，你可以根据需要进行类型转换
            resultMap.put(key, value);
        }
        resultMap.put("enable", config.getEnable());
        return resultMap;
    }

    /**
     * 获取配置
     *
     * @return 配置数据
     */
    @Override
    public Map<String, String> getConfig() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(CONFIGS.ALL_COLUMNS)
                .where(CONFIGS.TYPE.eq("basic"));
        List<Configs> configs = configsMapper.selectListByQuery(queryWrapper);

        return configs.stream()
                .collect(Collectors.toMap(Configs::getKey, Configs::getValue));
    }

    /**
     * 预处理数据
     *
     * @param param 参数
     * @param type  类型
     */
    private List<Configs> handelSettingParam(Map<String, String[]> param, String type) {
        List<Configs> list = new ArrayList<>();
        for (String key : param.keySet()) {
            Configs configs = new Configs();
            configs.setType(type);
            configs.setKey(key.replace("[]", ""));
            String[] values = param.get(key);
            if (values != null) {
                if (values.length == 1) {
                    configs.setValue(values[0]);
                } else {
                    List<String> valieList = new ArrayList<>(Arrays.asList(values));
                    configs.setValue(valieList.toString());
                }
            }
            list.add(configs);
        }
        return list;
    }

    /**
     * 返回已存设置的id
     *
     * @param type 类型
     * @param key  键
     * @return id
     */
    private Integer getSettingsId(String type, String key) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(CONFIGS.TYPE.eq(type))
                .and(CONFIGS.KEY.eq(key));
        Configs configs = configsMapper.selectOneByQuery(queryWrapper);
        return configs != null ? configs.getId() : null;
    }

    /**
     * 保存短信设置参数
     *
     * @param list 参数
     * @param type 类型
     * @return true:成功  false:失败
     */
    private boolean saveSmsSetting(List<Configs> list, String type) {
        Map<String, Object> smsConfig = list.stream()
                .filter(config -> !config.getKey().equals("type") && !config.getKey().equals("enable"))
                .collect(Collectors.toMap(
                        Configs::getKey,
                        Configs::getValue
                ));
        Integer enable = list.stream()
                .filter(config -> config.getKey().equals("enable"))
                .map(Configs::getValue)
                .findFirst().map(Integer::parseInt).orElse(0);
        String keys = list.stream()
                .filter(config -> config.getKey().equals("type"))
                .map(Configs::getValue)
                .findFirst().map(String::toString).orElse(String.valueOf(0));
        Configs newConfig = new Configs();
        newConfig.setType(type);
        newConfig.setKey(keys);
        newConfig.setEnable(enable);
        newConfig.setValue(smsConfig.toString());
        Integer id = getSettingsId(newConfig.getType(), newConfig.getKey());
        if (id != null) {
            newConfig.setId(id);
        }
        if (configsMapper.insertOrUpdateSelective(newConfig) > 0) {
            if (newConfig.getEnable() == 1) {
                UpdateChain.of(Configs.class)
                        .set(Configs::getEnable, 0)
                        .where(Configs::getId).ne(newConfig.getId())
                        .update();
            }
            return true;
        }
        return false;
    }
}

